package client;

import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;

import org.omg.CORBA.ORB;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.InvalidName;
import org.omg.CosNaming.NamingContextPackage.NotFound;

import centerModule.CenterService;
import centerModule.CenterServiceHelper;
import conf.Configuration;
import impl.UserServiceImpl;
import userModule.UserService;
import userModule.UserServiceHelper;

public class ToDoListClient {
	
	public static void main(String [] args) {
		ToDoListClient client = new ToDoListClient();
		client.init(args);
	}

	
	private Scanner  in ;
	private  CenterService centerService ;
	private  UserService userService;

	private org.omg.CORBA.Object objRef ;
	private NamingContextExt ncRef;
	
	public ToDoListClient() {
		
	}

	public void init(String[] args) {
		in = new Scanner(System.in);
		ORB  orb;
	      try{
	    	  if(args==null || args.length == 0) {
	    		  Properties props = new Properties();  
	    		// 生成一个ORB，并初始化，这个和Server端一样  
	    		  System.out.println("args is null ~~~");
				     props.put("org.omg.CORBA.ORBInitialPort", "1050");  
				     props.put("org.omg.CORBA.ORBInitialHost", "127.0.0.1");
				  // create and initialize the ORB
				    orb = ORB.init(args, props);
	    	  }else {
	    		  orb = ORB.init(args,null);
	    		  System.out.println("args is not null ~~~");
	    	  }
	    	 
	        // get the root naming context
	        objRef = 
		    orb.resolve_initial_references("NameService");
	        // Use NamingContextExt instead of NamingContext. This is 
	        // part of the Interoperable naming Service.  
	        ncRef = NamingContextExtHelper.narrow(objRef);
	 
	        // resolve the Object Reference in Naming
	        centerService = CenterServiceHelper.narrow(ncRef.resolve_str(Configuration.getConfig("service.center.name")));
	        
	        if(centerService!=null) {
	            System.out.println("Obtained a handle on server object: " + centerService);
	        	start();
	        }
	        else {
	        	System.out.println("start error!");
	        }
	        System.out.println("Obtained a handle on server object: " + centerService);
//	        helloImpl.shutdown();

		} catch (Exception e) {
	          System.out.println("ERROR : " + e) ;
		  e.printStackTrace(System.out);
		  }
	}
	
	public void start() throws Exception {
		int choice;
		String name,password;
		System.out.println("Welcome to toDoListAPP !");
		while(true) {
            System.out.println("1.Register\n2.Login\nelse.Exit");
            choice = in.nextInt();
            switch(choice){
            case 1:
            	System.out.println("please input name:");
            	name =  in.next();
            	System.out.println("please input password");
            	password =  in.next();
            	if(register(name,password)) {
            		System.out.println("register successfully!");
            		for(;service(name);) {
            			if(userService!=null) {
            				if(userService.save(name)) {
            					System.out.println("userService "+name+" save successfully");
            				}
            				else {
            					System.out.println("userService "+name+" save failed");
            				}
            			}
            		}
            	}else {
            		System.out.println("register failed! maybe "+name+" has bean registered!");
            	}
            	break;
            case 2:
            	System.out.println("please input name:");
            	name =  in.next();
            	System.out.println("please input password");
            	password =  in.next();
            	if(login(name, password)) {
            		System.out.println("login successfully");
            		for(;service(name);) {
            			if(userService!=null) {
            				if(userService.save(name)) {
            					System.out.println("userService "+name+" save successfully");
            				}
            				else {
            					System.out.println("userService "+name+" save failed");
            				}
            			}
            		}
            	}else {
            		System.out.println("login failed!");
            	}
            	break;
        	default:
        		if(centerService!=null && centerService.save()) {
        			System.out.println("centerService save successfully");
        		}
            	return;
            }
		}
	}
	
	private boolean service(String name) {
		if(userService==null)
			return false;
		
		int choice;
		String input;
		String startTime,endTime,value;
		String result=null;
		System.out.println("1.Add item\n" +
                "2.Query item\n" +
                "3.Show items\n" +
                "4.Delete item\n" +
                "5.Clear items\n" +
                "else.Logout");
        choice = in.nextInt();
        switch(choice) {
        case 1:
//        	读取，执行userService
        	System.out.println("please input startTime :");
        	input = in.nextLine();
        	while(input==null ||  input=="\n" || input== " " || input.length()==0) {
        	   input = in.nextLine();
        	}
        	startTime = input;
        	
        	System.out.println("please input endTime");

        	input = in.nextLine();
        	while(input==null ||  input=="\n" || input== " " || input.length()==0) {
         	   input = in.nextLine();
         	}
        	endTime =  input;
        	
        	
        	System.out.println("please input value");
        	input = in.nextLine();
        	while(input==null ||  input=="\n" || input== " " || input.length()==0) {
         	   input = in.nextLine();
         	}
        	value =  input;
        	if(userService.add(startTime, endTime, value)) {
        		System.out.println("add item successfully");
        	}
        	else {
        		System.out.println("add item failed");
        	}
        	return true;
        case 2:
        	System.out.println("please input startTime :");
        	input = in.nextLine();
        	while(input==null ||  input=="\n" || input== " " || input.length()==0) {
         	   input = in.nextLine();
         	}
        	startTime = input;
        	
        	System.out.println("please input endTime");
        	input = in.nextLine();
        	while(input==null ||  input=="\n" || input== " " || input.length()==0) {
         	   input = in.nextLine();
         	}
        	endTime =  input;
            result = userService.query(startTime, endTime);
        	System.out.print(result);
        	return true;
        case 3:
            result = userService.show();
            System.out.print(result);
        	return true;
        case 4:
        	System.out.println("please input item's value");
        	input = in.nextLine();
        	while(input==null ||  input=="\n" || input== " " || input.length()==0) {
         	   input = in.nextLine();
         	}
        	value =  input;
        	if(userService.delete(value)) {
        		System.out.println("delete successfully");
        	}
        	else {
        		System.out.println("can not find item "+value);
        	}
        	return true;
        case 5:
        	if(userService.clear()) {
        		System.out.println("clear successfully");
        	}
        	else {
        		System.out.println("clear failed");
        	}
        	return true;
    	default :
    		return false;
        }
	}
	
	
	/**
	 * 登录的目的是初始化userService
	 * @return
	 */
	private boolean login(String name,String password) {
		try {
			if(centerService.login(name,password)) {
				userService = UserServiceHelper.narrow(ncRef.resolve_str(name));
				if(userService!=null) {
					return true;
				}
				else {
					return false;
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	private boolean register(String name,String password) {
		try {
			if(centerService.register(name,password)) {
				userService = UserServiceHelper.narrow(ncRef.resolve_str(name));
				if(userService!=null) {
					return true;
				}
				else {
					return false;
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
}
